package cn.cs.controller;

import cn.cs.client.RestAppOrderClient;
import cn.cs.client.RestClientUserClient;
import cn.cs.client.RestRepOrderClient;
import cn.cs.client.RestRepairUserClient;
import cn.cs.common.DateUtil;
import cn.cs.common.Dto;
import cn.cs.common.DtoUtil;
import cn.cs.common.EmptyUtils;
import cn.cs.config.WXPayConfig;
import cn.cs.pojo.*;
import cn.cs.util.WeiXinUtil;
import cn.cs.util.WxAccessTokenUtils;
import com.sun.deploy.util.SessionState;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/wxRepSendTemp")
public class WxRepSendTempController {

    private Logger log = Logger.getLogger(WxRepSendTempController.class);

    @Resource
    private WXPayConfig wxPayConfig;
    @Resource
    private WxAccessTokenUtils wxAccessTokenUtils;
    @Resource
    private RestRepOrderClient restRepOrderClient;
    @Resource
    private RestAppOrderClient restAppOrderClient;
    @Resource
    private RestClientUserClient restClientUserClient;
    @Resource
    private RestRepairUserClient repairUserClient;
    /**
     * 发送模板消息
     * appId 公众账号的唯一标识
     * appSecret 公众账号的密钥
     * openId 用户标识
     * @throws UnsupportedEncodingException
     */
    @RequestMapping("/sendBill")
    @ResponseBody
    public Dto sendBill(HttpServletRequest request, HttpServletResponse response) throws  Exception {
        String repOrderId = request.getParameter("repOrderId");
        RepOrder repOrder =  restRepOrderClient.getRepOrderById(repOrderId);
        AppOrder appOrder = restAppOrderClient.getAppOrderById(repOrder.getApp_order_id());
//        Map<String,Object> order = mapper.getRepOrderById(repOrderId);
        ClientUser clientUser =     restClientUserClient.getClientUserById(appOrder.getUser_id());
        String wxOpenid = clientUser.getOpenId();
        if(EmptyUtils.isNotEmpty(repOrder)){
            String isSendBill = repOrder.getIs_send_bill();
            if("1".equals(isSendBill)){
                return  DtoUtil.returnFail("此订单已推送过账单，无需重复推送","002");
            }
//            AppOrder appOrder = restAppOrderClient.getAppOrderById(repOrder.getApp_order_id());
//            Map<String,Object> apporder = mapper.getAppOrderById(order.get("app_order_id").toString());
            boolean flage= false;
            if(EmptyUtils.isNotEmpty(appOrder.getIs_protect())){
                if("0".equals(appOrder.getIs_protect())){
                    ClientUser user = restClientUserClient.getClientUserByPhone(appOrder.getUser_phone());
                    if(EmptyUtils.isNotEmpty(user)){
                        wxOpenid = user.getOpenId();
                    }
                    else{
                        DtoUtil.returnFail("请用手机号："+appOrder.getUser_phone()+" 关注公众号后再提交","");
                    }
                }else{
                    flage = true;
                    wxOpenid =  clientUser.getOpenId();
                }
            }
            WxAccessToken wxAccessToken =  wxAccessTokenUtils.getWxAccessTokenOf2();
            if(EmptyUtils.isEmpty(wxAccessToken)){
                return  DtoUtil.returnFail("获取accesstoken失败","002");
            }
            String access_token = wxAccessToken.getAccessToken();
            String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+access_token;
            WxTemplate temp = new WxTemplate();
            temp.setUrl("https://www.zzzsyh.com/index.html#/pay?orderId="+repOrderId);
            temp.setTouser(wxOpenid);
            temp.setTopcolor("#000000");
            temp.setTemplate_id("NpUyClYrnNby3z87sqvkzUWhUccQ3sBqGpZRecb9RS4");
            Map<String, TemplateData> m = new HashMap<String,TemplateData>();
            TemplateData first = new TemplateData();
            if(flage){
                first.setValue("用户:"+appOrder.getUser_name() +"\n电话:"+appOrder.getUser_phone()+"\n地址:"+appOrder.getUser_address() +"\n服务单已完成" );
            }else{
                first.setValue("尊敬的用户,您好：\n" +
                        "\n" +
                        "您预约的服务单已经完成\n" );
            }

            first.setColor("#000000");
            m.put("first", first);
            TemplateData keyword1 = new TemplateData();
            keyword1.setValue("家电服务费用账单");
            keyword1.setColor("#000000");
            m.put("keyword1", keyword1);
            TemplateData keyword2 = new TemplateData();
            keyword2.setValue("￥"+repOrder.getAll_cost()+"元");
            keyword2.setColor("#000000");
            m.put("keyword2", keyword2);
            TemplateData keyword3 = new TemplateData();
            keyword3.setValue("￥"+repOrder.getAll_cost()+"元");
            keyword3.setColor("#000000");
            m.put("keyword3", keyword3);
            TemplateData keyword4 = new TemplateData();
            TemplateData remark = new TemplateData();
            remark.setColor("#000000");
            m.put("remark", remark);
            temp.setData(m);
            String jsonString = JSONObject.fromObject(temp).toString();
            JSONObject jsonObject = WeiXinUtil.httpRequest(url, "POST", jsonString);
            int result = 0;
            if (null != jsonObject) {
                if (0 != jsonObject.getInt("errcode")) {
                    result = jsonObject.getInt("errcode");
//                log.error("错误 errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg"));
                }else{
//                    order.put("is_send_bill","1");
                    repOrder.setIs_send_bill("1");
                    restRepOrderClient.updateRepOrderBillState(repOrder);
                }
            }
            log.info("模板消息发送结果："+result);
            return DtoUtil.returnSuccess();
        }
        else{
            return  DtoUtil.returnFail("此维修单不存在","002");
        }
    }

    @RequestMapping("/sendTestBill")
    @ResponseBody
    public Dto sendTestBill(HttpServletRequest request, HttpServletResponse response) throws  Exception {
        String repOrderId = request.getParameter("repOrderId");
        String all_cost = request.getParameter("all_cost");
//        Map<String,Object> order = mapper.getRepOrderById(repOrderId);
        RepOrder repOrder = restRepOrderClient.getRepOrderById(repOrderId);
        AppOrder appOrder = restAppOrderClient.getAppOrderById(repOrder.getApp_order_id());
        ClientUser user = restClientUserClient.getClientUserById(appOrder.getUserId());
        String wxOpenid = user.getOpenId();
        if(EmptyUtils.isNotEmpty(repOrder)){
            String isSendBill =repOrder.getIs_send_bill();
            if("1".equals(isSendBill)){
                return  DtoUtil.returnFail("此订单已推送过账单，无需重复推送","002");
            }
            WxAccessToken wxAccessToken =  wxAccessTokenUtils.getWxAccessTokenOf2();
            if(EmptyUtils.isEmpty(wxAccessToken)){
                return  DtoUtil.returnFail("获取accesstoken失败","002");
            }
            String access_token = wxAccessToken.getAccessToken();
            String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+access_token;
            WxTemplate temp = new WxTemplate();
            temp.setUrl("https://www.zzzsyh.com/index.html#/pay_over?orderId="+repOrderId+"&testCost="+all_cost);
            temp.setTouser(wxOpenid);
            temp.setTopcolor("#000000");
            temp.setTemplate_id("NpUyClYrnNby3z87sqvkzUWhUccQ3sBqGpZRecb9RS4");
            Map<String, TemplateData> m = new HashMap<String,TemplateData>();
            TemplateData first = new TemplateData();
            first.setValue("尊敬的用户,您好：\n" +
                    "\n" +
                    "您预约的服务单已经完成\n" );
            first.setColor("#000000");
            m.put("first", first);
            TemplateData keyword1 = new TemplateData();
            keyword1.setValue("家电服务检测费用账单");
            keyword1.setColor("#000000");
            m.put("keyword1", keyword1);
            TemplateData keyword2 = new TemplateData();
            keyword2.setValue("￥"+repOrder.getAll_cost()+"元");
            keyword2.setColor("#000000");
            m.put("keyword2", keyword2);
            TemplateData keyword3 = new TemplateData();
            keyword3.setValue("￥"+repOrder.getAll_cost()+"元");
            keyword3.setColor("#000000");
            m.put("keyword3", keyword3);
            TemplateData remark = new TemplateData();
            remark.setColor("#000000");
            m.put("remark", remark);
            temp.setData(m);
            String jsonString = JSONObject.fromObject(temp).toString();
            JSONObject jsonObject = WeiXinUtil.httpRequest(url, "POST", jsonString);
            int result = 0;
            if (null != jsonObject) {
                if (0 != jsonObject.getInt("errcode")) {
                    result = jsonObject.getInt("errcode");
//                    log.error("错误 errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg"));
                }else{
                    repOrder.setIs_send_bill("1");
//                    order.put("is_send_bill","1");
                    restRepOrderClient.updateRepOrder(repOrder);
//                    mapper.updateRepOrderBillState(order);
                }
            }
            log.info("模板消息发送结果："+result);
            return DtoUtil.returnSuccess();
        }
        else{
            return  DtoUtil.returnFail("此维修单不存在","002");
        }
    }

    @RequestMapping("/send_template")
    @ResponseBody
    public Dto send_template(HttpServletRequest request, HttpServletResponse response) throws  Exception {
        String orderId = request.getParameter("orderId");
        String type = request.getParameter("type");
        RepOrder repOrder = restRepOrderClient.getRepOrderById(orderId);
        AppOrder appOrder = restAppOrderClient.getAppOrderById(repOrder.getApp_order_id());
//        Map<String,Object> order = mapper.getRepOrderById(orderId);
//        Map<String,Object> appOrder = mapper.getAppOrderById(order.get("app_order_id").toString());
        WxAccessToken wxAccessToken =  wxAccessTokenUtils.getWxAccessTokenOf2();
        if(EmptyUtils.isEmpty(wxAccessToken)){
            return  DtoUtil.returnFail("获取accesstoken失败","002");
        }
        String access_token = wxAccessToken.getAccessToken();
        String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+access_token;
        ClientUser user = restClientUserClient.getClientUserById(appOrder.getUser_id());
        if(EmptyUtils.isNotEmpty(type)){

            WxTemplate temp = new WxTemplate();
            temp.setTouser(user.getOpenId());
            temp.setTopcolor("#000000");
            temp.setTemplate_id("74WuIFjLI-ev9ojllKOC6h4RgqUObjcgrgqGLRzlc68");
            Map<String, TemplateData> m = new HashMap<String,TemplateData>();
            TemplateData first = new TemplateData();
            first.setValue("师傅已和客户约好上门服务时间，详情如下");
            first.setColor("#000000");
            m.put("first", first);
            TemplateData keyword1 = new TemplateData();
            keyword1.setValue(appOrder.getService_name());
            keyword1.setColor("#000000");
            m.put("keyword1", keyword1);
            TemplateData keyword2 = new TemplateData();
            keyword2.setValue(appOrder.getUser_address());
            keyword2.setColor("#000000");
            m.put("keyword2", keyword2);

            TemplateData keyword3 = new TemplateData();
            keyword3.setValue(appOrder.getOrder_date()+" "+appOrder.getOrder_time());
            keyword3.setColor("#000000");
            m.put("keyword3", keyword3);
            TemplateData remark = new TemplateData();
            remark.setValue("服务进行中，请等待...");
            remark.setColor("#000000");
            m.put("remark", remark);
//        temp.setUrl("https://www.zzzsyh.com/index.html#/rates?first_b="+pid+"&area="+areaId);
            temp.setData(m);
            String jsonString = JSONObject.fromObject(temp).toString();
            JSONObject jsonObject = WeiXinUtil.httpRequest(url, "POST", jsonString);
            int result = 0;
            if (null != jsonObject) {
                if (0 != jsonObject.getInt("errcode")) {
                    result = jsonObject.getInt("errcode");
//                    log.error("错误 errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg"));
                }
            }
            log.info("模板消息发送结果："+result);
        }else{
            WxTemplate temp = new WxTemplate();
            temp.setTouser(user.getOpenId());
            temp.setTopcolor("#000000");
            temp.setTemplate_id("IdAMbMuScAgpe_8koKOg_IpwVsBad_KxCTX9S7BQMdE");
            Map<String, TemplateData> m = new HashMap<String,TemplateData>();
            TemplateData first = new TemplateData();
//        if("2".equals(appOrder.get("user_type").toString())){
//            first.setValue("用户："+appOrder.get("user_name").toString()+"\n电话："+appOrder.get("user_phone").toString()+"\n地址："+appOrder.get("user_address").toString()+"\n服务单已接单");
//        }else{
//            first.setValue("订单状态提醒");
//        }
            first.setValue("用户："+appOrder.getUserName()+"\n电话："+appOrder.getUser_phone()+"\n地址："+appOrder.getUser_address()+"\n服务单已接单");
            first.setColor("#000000");
            m.put("first", first);
            TemplateData keyword1 = new TemplateData();
            keyword1.setValue(appOrder.getService_name());
            keyword1.setColor("#000000");
            m.put("keyword1", keyword1);
            TemplateData keyword2 = new TemplateData();
            keyword2.setValue(appOrder.getId());
            keyword2.setColor("#000000");
            m.put("keyword2", keyword2);

            TemplateData keyword3 = new TemplateData();
            keyword3.setValue("已接单");
            keyword3.setColor("#000000");
            m.put("keyword3", keyword3);
            TemplateData keyword4 = new TemplateData();
            keyword4.setValue(DateUtil.format(new Date(),"yyyy-MM-dd HH:mm:ss"));
            keyword4.setColor("#000000");
            m.put("keyword4", keyword4);
            String personName = "";
            RepairUser repairUser = repairUserClient.getRepairUserById(repOrder.getRep_user_id());
            if(repairUser.getPersonName().length() == 3 || repairUser.getPersonName().length() == 2){
                personName = repairUser.getPersonName().substring(0,1)+"师傅";
            }
            if(repairUser.getPersonName().length() == 4 ){
                personName = repairUser.getPersonName().substring(0,2)+"师傅";
            }
            if("".equals(personName)){
                personName = repairUser.getPersonName();
            }
            TemplateData keyword5 = new TemplateData();
            keyword5.setValue(personName);
            keyword5.setColor("#000000");
            m.put("keyword5", keyword5);
            TemplateData remark = new TemplateData();
            remark.setValue("服务进行中，请等待...");
            remark.setColor("#000000");
            m.put("remark", remark);
//        temp.setUrl("https://www.zzzsyh.com/index.html#/rates?first_b="+pid+"&area="+areaId);
            temp.setData(m);
            String jsonString = JSONObject.fromObject(temp).toString();
            JSONObject jsonObject = WeiXinUtil.httpRequest(url, "POST", jsonString);
            int result = 0;
            if (null != jsonObject) {
                if (0 != jsonObject.getInt("errcode")) {
                    result = jsonObject.getInt("errcode");
//                    log.error("错误 errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg"));
                }
            }
            log.info("模板消息发送结果："+result);
        }

        return DtoUtil.returnSuccess();
    }

    @RequestMapping("/sendTestReport")
    @ResponseBody
    public Dto sendTestReport(HttpServletRequest request, HttpServletResponse response) throws  Exception {
        String reportId = request.getParameter("reportId");
        RepairTestReport report = restRepOrderClient.getTestReportByOrderId(reportId);
        RepOrder repOrder = restRepOrderClient.getRepOrderById(reportId);
        AppOrder appOrder = restAppOrderClient.getAppOrderById(repOrder.getApp_order_id());
        log.info("reportId:"+reportId);
        log.info("report:"+report);
        String wxOpenid ="";
        if(EmptyUtils.isNotEmpty(report.getIs_protect())){
            if("0".equals(report.getIs_protect())){

                ClientUser clientUser = restClientUserClient.getClientUserByPhone(appOrder.getUser_phone());
                if(EmptyUtils.isNotEmpty(clientUser)){
                    wxOpenid = clientUser.getOpenId();
                }else{
                    DtoUtil.returnFail("请用手机号："+appOrder.getUser_phone()+" 关注公众号后再提交","");
                }
            }else{
                ClientUser user = restClientUserClient.getClientUserById(appOrder.getUser_id());
                wxOpenid =  user.getOpenId();
            }
        }else{
            ClientUser user = restClientUserClient.getClientUserById(appOrder.getUser_id());
            wxOpenid = user.getOpenId();
        }
        WxAccessToken wxAccessToken =  wxAccessTokenUtils.getWxAccessTokenOf2();
        if(EmptyUtils.isEmpty(wxAccessToken)){
            return  DtoUtil.returnFail("获取accesstoken失败","002");
        }
        String access_token = wxAccessToken.getAccessToken();
        String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+access_token;
        WxTemplate temp = new WxTemplate();
        temp.setUrl("https://www.zzzsyh.com/index.html#/testreport?repOrderId="+reportId);
        temp.setTouser(wxOpenid);
        temp.setTopcolor("#000000");
        temp.setTemplate_id("P2zB8ART4N-jW5F-ou0pqixagdpAmSEUPK2RV7W6-Og");
        Map<String, TemplateData> m = new HashMap<String,TemplateData>();
        TemplateData first = new TemplateData();
        first.setValue("尊敬的用户,您好\n" +
                "\n" +
                "请查看您的维修检查报告\n" +
                "");
        first.setColor("#000000");
        m.put("first", first);
        TemplateData keyword1 = new TemplateData();
        keyword1.setValue(appOrder.getFault_name());
        keyword1.setColor("#000000");
        m.put("keyword1", keyword1);
        TemplateData keyword2 = new TemplateData();
//        keyword2.setValue(report.get("fault_comment").toString());
        keyword2.setValue("已检测");
        keyword2.setColor("#000000");
        m.put("keyword2", keyword2);
        TemplateData remark = new TemplateData();
        remark.setValue("同样价格，星级享受！我们将竭诚为您服务！");
        remark.setColor("#000000");
        m.put("remark", remark);
        temp.setData(m);
        String jsonString = JSONObject.fromObject(temp).toString();
        JSONObject jsonObject = WeiXinUtil.httpRequest(url, "POST", jsonString);
        System.out.println(jsonObject);
        int result = 0;
        if (null != jsonObject) {
            if (0 != jsonObject.getInt("errcode")) {
                result = jsonObject.getInt("errcode");
//                log.error("错误 errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg"));
            }
        }
        log.info("模板消息发送结果："+result);
        return DtoUtil.returnSuccess();
    }



}
